package com.cms.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.entity.base.BaseMenu;
import com.cms.enums.MenuType;
import lombok.EqualsAndHashCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Entity - 菜单
 * 
 * 
 * 
 */
@SuppressWarnings("serial")
@EqualsAndHashCode(callSuper = false)
@TableName("cms_menu")
public class Menu extends BaseMenu {
	/** 树路径分隔符 */
	public static final String TREE_PATH_SEPARATOR = ",";
    
    
	/**
	 * 下级菜单
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private List<Menu> children;
	
	/**
	 * 上级菜单
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private Menu parent;


	/**
	 * 获取类型名称
	 *
	 * @return 类型名称
	 */
	public String getTypeName(){
		return MenuType.typeValueMap.get(getType()).getText();
	}
	
	/**
	 * 获取下级菜单地址
	 * 
	 * @return 下级菜单地址
	 */
	public List<String> getChildrenUrls(){
		List<String> urls = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(getChildren())){
			for(Menu menu : getChildren()){
				urls.add(menu.getUrl());
			}
		}
		return urls;
	}
	
	/**
	 * 获取下级菜单
	 * 
	 * @return 下级菜单
	 */
	public List<Menu> getChildren() {
	    if(children == null){
			List<Map<String,Object>> maps = SqlRunner.db().selectList("select * from cms_menu where parentId={0} order by sort desc",getId());
			children = maps.stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Menu.class)).collect(Collectors.toList());
	    }
		return children;
	}
	
	/**
	 * 获取上级菜单
	 * @return	上级菜单
	 */
	public Menu getParent(){
	    if(parent == null){
			Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_menu where id={0}",getParentId());
			parent = JSON.parseObject(JSON.toJSONString(map), Menu.class);
	    }
		return parent;
	}
	
	

	/**
	 * 获取所有上级分类ID
	 * 
	 * @return 所有上级分类ID
	 */
	public Integer[] getParentIds() {
		String[] treePaths = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR);
		Integer[] result = new Integer[treePaths.length];
		for (int i = 0; i < treePaths.length; i++) {
			result[i] = Integer.valueOf(treePaths[i]);
		}
		return result;
	}
	
	
	/**
	 * 设置值
	 * 
	 */
	public void setValue() {
		if (getParentId() != null) {
			setTreePath(getParent().getTreePath() + getParent().getId() + Category.TREE_PATH_SEPARATOR);
		} else {
			setTreePath(Category.TREE_PATH_SEPARATOR);
		}
		setGrade(getParentIds().length);
	}
	
}
